<?php
//------------------------------------------------------------------------------
//
//   [ GETTING USERS ]
//
//------------------------------------------------------------------------------

function get_users($filter=false)
{

   $db = mysql_init();
   
   $q = (!$filter) ? 'select `users`.*, `levels`.`num` as `level`
                                                                  from `users`
                                                                  inner join `levels` on `levels`.`id`=`users`.`level_id`
                                                                  order by `levels`.`num` desc, `users`.`name`'
                   :
                     "select `users`.*, `levels`.`num` as `level`
                                                                  from `users`
                                                                  inner join `levels` on `levels`.`id`=`users`.`level_id`
                     where (`users`.`name` like '%".$filter."%') or (`login` like '%".$filter."%') order by `levels`.`num` desc, `users`.`name`";
                          
   $users = $db->select($q);
   
   return $users;
}


function get_users_by_level($level)
{
	$db = mysql_init();
   
   $q = 'select `users`.*, `levels`.`num` as `level` from `users` inner join `levels` on `levels`.`id`=`users`.`level_id`
																						where `levels`.`num` >= ?d
                                                                  order by `levels`.`num` desc, `users`.`name`';
   $users = $db->select($q, $level);
   
   return $users;
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------

function get_userlevel($level_id)
{
   if(!$level_id>0) return 0;

   $lv = get_rfc_item('levels', $level_id);

   return $lv['num'];
}

//------------------------------------------------------------------------------


function is_admin($user)
{
   return isset($user['login']) && preg_match('/\s'.$user['login'].'\s/', _admins); // ololo
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------


function avd()
{
   $args = func_get_args();
   
   if( is_admin(array_shift($args)) ) var_dump($args);
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------


function get_user($uid, $lgn='nono')
{
   if( !($uid>0 || $lgn!='nono') ) return false;

   $db = mysql_init();
   $q = 'select `users`.*, `levels`.`num` as `level`
                                                   from `users`
                                                   inner join `levels` on `levels`.`id`=`users`.`level_id`
                                                   where `users`.`id`=?d or `login`=? limit 1';

   $user = $db->selectRow($q, $uid, $lgn);
   
   if( is_array($user) && isset($user['id']) )  return $user;
   else return no_user();
}

//------------------------------------------------------------------------------

function get_username($uid)
{
   $user = get_user($uid);
   
   if( isset($user['name']) ) return $user['name'];
   else return 'n/a';
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------

function remove_user($uid)
{
   if( !($uid>0) ) return false;
   
   $db = mysql_init();
   
   $q = 'delete from `users` where `id`=?d limit 1';
   $db->query($q, $uid);
   
   $q = 'delete from `user_rights` where user_id=?d';
   $db->query($q, $uid);
   
   return true;
}


//------------------------------------------------------------------------------
//------------------------------------------------------------------------------


function is_user($user, $simple=1)
{
   if(!isset($user['id'])) return false;
   
       if($user['id']>0 && $simple==1) return true;
   elseif($user['id']>0 && $simple==0)
   {
      $dbuser = get_user($user['id']);
      
      if( isset($dbuser['id']) ) return true;
      else return false;
   }
   else return false;
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// gettin' rights as is for system use

function get_user_rights_nat($uid)
{
   if( !($uid>0 ) ) return false;

   $db = mysql_init();
   $q = 'select * from `user_rights` where `user_id`=?d order by `right_id`';
   
   $user_rights = $db->select($q, $uid);

   return $user_rights;
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------


function get_user_rights($uid)
{
   if( !($uid>0 ) ) return false;
   
   
   $db = mysql_init();

   $q = 'select  `modules`.`keyword` as array_key_1,
                 `rights`.`keyword` as array_key_2,
                 `modules`.*,
                 `rights`.*,
                 `user_rights`.*
                 
                 from `modules`
            inner join `rights` on `modules`.`id` = `rights`.`module_id`
            inner join `user_rights` on `rights`.`id` = `user_rights`.`right_id`
            where `user_rights`.`user_id` = ?d
            ';

   $user_rights = $db->select($q, $uid);

   return $user_rights;
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------


function get_user_and_his_rights($uid)
{
   $user = get_user($uid);
   
   if(!is_array($user)) return false;
   
   $user['rights'] = get_user_rights($uid);

   return $user;
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------


function get_users_and_their_rights($filter=false)
{
   $users = get_users($filter);
   $c = count($users);
   
   for($k=0; $k<$c; $k++)
   {
      $users[$k]['rights'] = get_user_rights($users[$k]['id']);
   }
   
   return $users;
}


//------------------------------------------------------------------------------
//------------------------------------------------------------------------------

function check_user_right($module, $right, $urights)
{
   if( !is_array($urights) ) return false;
   
   if( isset($urights[$module][$right]) ) return true;
   
   else return false;
}




//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//
//    [ EDITING USERS ]
//
//
//------------------------------------------------------------------------------


//------------------------------------------------------------------------------


function check_login($login, $flag=false)
{
   $login = strtolower($login);
   $login = preg_replace('/[^a-z0-9\.\-\_\@]/i', '', $login);

   if(strlen($login)<_login_length) return false;
   
   
   $inbase = get_users($login);
   
       if(!$flag && count($inbase)>0) return false;   // this login isn't used?
   elseif( $flag && count($inbase)>0) return $login;  // this login exists?
   
   return $login;
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------

function check_password($pass)
{
   if(strlen($pass) < _password_length) return false;
   else return true;
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------

function check_name($name, $dont_chk_length=false)
{
   $name = preg_replace('/[^ a-zа-яё\-\.\@]/iu', '', $name);
   
   if(strlen($name)<5 && !$dont_chk_length) return false;

   return $name;
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------


function check_email($email)
{
   if (!strstr($email, '@')) return '';
   
   $email = strtolower($email);
   $email = preg_replace('/[^0-9a-z\-\_\.\@]/i', '', $email);
   
   return $email;
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------


/*
$user:

   [id] => 0=new
   [login] => login
   [name] => the name of the user
   [comment] => owch...
   [ban] => 0
   [pass] => md5

*/

function edit_user_info($user)
{
   if(!is_array($user) || !isset($user['id'])) return false;

   $user['id']    = justdigs($user['id']);
   $user['login'] = check_login($user['login'], ($user['id']>0));
   $user['name']  = check_name ($user['name']);
   $user['email'] = check_email($user['email']);
   $user['ban']   = ($user['ban'] == 1) ? 1 : 0;
   $user['pass']  = preg_replace('/[^0-9a-f]/i', '', $user['pass']);

   if(isset($user['level'])) unset($user['level']);


   $r = 'error';

   if($user['login'] && $user['name'] && $user['pass'])
   {
      $db = mysql_init();

      if($user['id']==0) // ------------------------------- // v New user
      {
         $q = 'insert into `users` (?#) values(?a)';
         $r =
             $db->query($q, array_keys($user), array_values($user));
             
      }
      elseif($user['id']>0) // ---------------------------- // v Edit user
      {
         $q = 'update `users` set ?a where id=?d';
         $r =
             $db->query($q, $user, $user['id']);
             
         $r = ($r == 'error') ? 'ok' : $r;
      }
   }

   return $r;
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------

/*
   $rights:

   [0] => [right_id]
        ...
   [n] => [right_id]

*/


function compare_rights($current_uid, $new_rights)
{
   if( !($current_uid>0) || !is_array($new_rights) ) return '';
   
   $u1_rights = get_user_rights_nat($current_uid);
   $u2_rights = array();
   
   $c1 = count($u1_rights);
   $c2 = count($new_rights);

   for($i=0; $i<$c1; $i++)
   {
      for($j=0; $j<$c2; $j++)
      {
         if( $new_rights[$j] == $u1_rights[$i]['right_id'] ) $u2_rights[] = $new_rights[$j];
      }
   }

   return $new_rights;
}

//------------------------------------------------------------------------------

function edit_user_rights($uid, $rights, $current_user)
{
   if( !($uid>0) && !is_array($rights) && !isset($current_user['id']) ) return false;

   $rights = compare_rights($current_user['id'], $rights);

   $db = mysql_init();


/* clear old rights
*/
   $q  = 'delete from `user_rights` where user_id=?d';

   $db->query($q, $uid);


/* insert new rights
*/
   $q = 'insert into `user_rights` (`id`, `user_id`, `right_id`) values(null, ?d, ?d)';


   $c = count($rights);
   
   for($i=0; $i<$c; $i++)
   {
      $rid = preg_replace('/[^0-9]/', '', $rights[$i]);
   
      $db->query($q, $uid, $rid);
   }
   
   return 0;
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------



//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//
// [ HTML FUNCTIONS ]
//
//                userlist, user-form, etc...
//
//------------------------------------------------------------------------------


//--------------------------------------

//          [ USER-PAGE ]

//--------------------------------------

function get_last_users_bugs($userid, $count=10)
{
   if( !($userid>0) ) return get_template('userpage-last10bugs-nothing.html');
   
   $count = ( 0 < $count || $count > 100 ) ? 10 : $count; //  last 1 - 100, default 10;
   
   $bugs = get_users_bugs($userid, $count);
   
   $count = count($bugs); // warning!

   if(!($count>0)) return get_template('userpage-last10bugs-nothing.html');
   
   
   $bugstable_tpl = get_template('userpage-last10bugs-table.html');
// $bugstable_kwords = "_ROWS_";
   
   $bugsrow_tpl = get_template('userpage-last10bugs-row.html');
   $bugstable_kwords = array('_ID_', '_TITLE_', '_DATE_');
   
   
   $rows = '';

   for($i=0; $i<$count; $i++)
   {
      $r = array( $bugs[$i]['id'],
                  $bugs[$i]['title'],
                  $bugs[$i]['date']
                  );

      $rows .= str_replace($bugstable_kwords, $r, $bugsrow_tpl);
   }
   
   $html = str_replace('_ROWS_', $rows, $bugstable_tpl);
   
   return $html;
}

//------------------------------------------------------------------------------


function get_last_users_comments($userid, $count=10)
{
   if( !($userid>0) ) return get_template('userpage-last10comments-nothing.html');

   $count = ( 0 < $count || $count > 100 ) ? 10 : $count; //  last 1 - 100, default 10;

   $cmts = get_users_comments($userid, $count);

   $count = count($cmts); // warning!
   
   if(!($count>0)) return get_template('userpage-last10comments-nothing.html');
   

   $cmtstable_tpl = get_template('userpage-last10bugs-table.html');  // attention! we used tpl of ^ _bugs_ ^

   $cmtsrow_tpl = get_template('userpage-last10comments-row.html');
   $cmtstable_kwords = array('_BID_', '_CID_', '_TEXTPART_', '_DATE_');

   $rows = "";

   for($i=0; $i<$count; $i++)
   {
      $quote = (strlen($cmts[$i]['text']) <= 50) ? justwords($cmts[$i]['text']) : justwords( trim( mb_substr($cmts[$i]['text'], 0, 50) ) ) .'...';
      
      $r = array( $cmts[$i]['bug_id'],
                  $cmts[$i]['id'],
                  $quote,
                  $cmts[$i]['date']
                  );

      $rows .= str_replace($cmtstable_kwords, $r, $cmtsrow_tpl);
   }

   $html = str_replace('_ROWS_', $rows, $cmtstable_tpl);

   return $html;
}

//------------------------------------------------------------------------------



function html_userpage($user, $canedit=false, $canviewall=false, $canremove=false)
{
   if(!is_array($user) || !isset($user['id'])) return get_template('error_nouser.html');
   $usertable_tpl = get_template('userpage.html');
   
   $usertable_kwords = array('_EDITLINK_', '_REMOVELINK_', '_ALLLINK_', '_NAME_', '_LOGIN_', '_LEVEL_', '_EMAIL_', '_COMMENT_', '_LAST10BUGS_', '_LAST10COMMENTS_');
   

   $editlink = $canedit ? get_template('userpage-edit-link.html') : '';
   $editlink = str_replace('_ID_', $user['id'], $editlink);
   
   $removelink = $canremove ? get_template('userpage-remove-link.html') : '';
   $removelink = str_replace('_ID_', $user['id'], $removelink);
   
   $alllink = $canviewall ? get_template('userpage-viewall-link.html') : '';

   $last10bugs = get_last_users_bugs($user['id']);
   $last10cmts = get_last_users_comments($user['id']);

   $r = array( $editlink,
               $removelink,
               $alllink,
               $user['name'],
               $user['login'],
               get_rfc_item_name('levels', $user['level_id']),
               $user['email'],
               $user['comment'],
               $last10bugs,
               $last10cmts
               );
               
               
   $html = str_replace($usertable_kwords, $r, $usertable_tpl);

   return $html;
}




//--------------------------------------

//          [ RIGHTS-CELL OF USER-FORM ]

//--------------------------------------


function html_edit_user_rights_list($rights, $urights, $current_user)
{
   if( !is_array($rights) ) return '';

   if( !isset($current_user['rights']) || !check_user_right('sections', 'edit_rights', $current_user['rights']) ) return '';

   $module_html_kwords = array('_MODULENAME_', '_RIGHTS_');
   $module_html_row= get_template('userpage-rights-section.html');

   $right_html_kwords = array('_ID_', '_CHECKED_', '_HIDDEN_', '_NAME_');
   $right_html_row = get_template('userpage-rights-row.html');

   $html = '';

   foreach($rights as $key => $module)
   {
      $m = array($module['name'], ''); // look at the next `foreach` to find what is $m[1] (rights list)

      foreach($module['rights'] as $rkey => $right)
      {
         $checked = check_user_right($key, $rkey, $urights) ? 'checked' : '';

         $canedit = is_admin($current_user) || check_user_right($key, $rkey, $current_user['rights']) ? '' : 'x'; // css-class for <label>

         $r = array( $right['id'],
                     $checked,
                     $canedit,
                     $right['name']);

         $m[1] .= str_replace($right_html_kwords, $r, $right_html_row);
      }

      $html .= str_replace($module_html_kwords, $m, $module_html_row);
   }
   
   
   $tpl = get_template('userpage-rights.html');
   $kws = array('_VISIBILITY_', '_RIGHTS_');

   //$canedit = ($canedit) ? 'x' : ''; // x = css class (hidden
   
   $html = str_replace($kws, array('', $html), $tpl);

   return $html;
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------




//-----------------------

//          [ USER-FORM ]

//-----------------------


function html_edit_user_form($user='new', $current_user)
{
   $adminmode = is_admin($current_user);
   
   $default_user = new_user_array();
    
   if($user == 'new') $user = $default_user;
   
   $rights = get_modules_and_rights();
   $urights = isset($user['rights']) ? $user['rights'] : '';

   $form_html = get_template('userpage-x-info-form.html');

   $form_kwords = array( '_ALLLINK_',
                         '_BASEDOMAIN_',
                         '_USERID_',
                         '_USERNAME_',
                         '_USERLOGIN_',
                         '_USERLEVEL_',
                         '_USEREMAIL_',
                         '_USERCOMMENT_',
                         '_USERPASS_',
                         '_USERLOCK_',
                         '_RIGHTS_',
                         '_DEFNAME_',
                         '_DEFLOGIN_',
                         '_DEFEMAIL_',
                         '_DEFCOMMENT_',
                         '_OLDLEVEL_');
                         
   $userlock = ($user['ban']==1) ? 'checked' : '';
   
   $rights_html = ( $adminmode || $user['id']!=$current_user['id']) ? html_edit_user_rights_list($rights, $urights, $current_user) : '';
   
   $levels_html = ( $adminmode || ($user['id']!=$current_user['id'] && $user['level']<=$current_user['level']) )
                                                                  ?
                                                                  str_replace('_USERLEVELS_', list_ref_opts('levels', $user['level_id'], $current_user['level']), get_template('userpage-x-info-form-level.html'))
                                                                  :
                                                                  get_rfc_item_name('levels', $user['level_id']);
                                                                  

   $alllink = check_user_right('sections', 'edit_users', $current_user['rights']) ? get_template('userpage-viewall-link.html') : '';
   
   
   $r = array( $alllink,
               _basedomain,
               $user['id'],
               $user['name'],
               $user['login'],
               $levels_html,
               $user['email'],
               $user['comment'],
               $user['pass'],
               $userlock,
               $rights_html,
               $default_user['name'],
               $default_user['login'],
               $default_user['email'],
               $default_user['comment'],
               $user['level_id']);
               
   $html = str_replace($form_kwords, $r, $form_html);

   return $html;
}



//------------------------------------------------------------------------------
//------------------------------------------------------------------------------



//-----------------------=

//          [ USERS LIST ]

//-----------------------=


function html_userlist($users, $cancreate=false, $justtable=false)
{

   $html_userlist_row = get_template('userlist-row.html');
   $kwords_userlist_row = array('_LEVEL_', '_NAME_', '_LOGIN_', '_LOCK_');
   

   $html_userlist_table = get_template('userlist-table.html');
   $kwords_userlist_table = array('_PAGEBAR_', '_ROWS_');
   
   
   $html_userlist = get_template('userlist.html');
   $kwords_userlist = array('_CREATELINK_', '_USERSTABLE_');

//------------------------------------------------------------------------------
   
// let's go...   
   
   $rows = '';
   
   $c = count($users);
   
   for($i=0; $i<$c; $i++)
   {
      $user = array( get_rfc_item_name('levels', $users[$i]['level_id']),
                     $users[$i]['name'],
                     $users[$i]['login'],
                     ( $users[$i]['ban']==1 ? 'Y' : 'N') );
      
      $rows .= str_replace($kwords_userlist_row, $user, $html_userlist_row);
   }


   $pagebar = '';

   $userstable = str_replace($kwords_userlist_table, array($pagebar, $rows), $html_userlist_table);
   
   if($justtable) return $userstable; // 4 search


   $createlnk = ($cancreate) ? get_template('userlist-createuser-link.html') : '&nbsp;<!-- can`t create user -->';

   $userlist = str_replace($kwords_userlist, array($createlnk, $userstable), $html_userlist);
   

   return $userlist;
}


//------------------------------------------------------------------------------
//------------------------------------------------------------------------------



//------------------------------=

//          [ REGISTERING USER ]

//------------------------------=

function html_registerform($user)
{
   $user = (is_array($user) && isset($user['name']) ) ? $user : new_user_array();
   
   
   $tpl = get_template('user_register_form.html');
   $kws = array('_NAME_', '_LOGIN_', '_EMAIL_', '_COMMENT_', '_BASEDOMAIN_');
   
   $r = array( $user['name'], $user['login'], $user['email'], $user['comment'], _basedomain);

   return str_replace($kws, $r, $tpl);
   
}







?>
